<template>
  <div class="login-container" id="app">
    <h2>登录</h2>
    <form @submit.prevent="login">
      <div class="form-control">
        <label for="loginForm.username">用户名:</label>
        <input type="text" id="" v-model="loginForm.username" required>
      </div>
      <div class="form-control">
        <label for="loginForm.password">密码:</label>
        <input type="password" id="password" v-model="loginForm.password" required>
      </div>
      <button type="submit" class="login-btn">登录</button>
      <router-link to="/register" class="register-link">没有账号？去注册</router-link>
    </form>
    <!-- <p v-if="error" class="error-message">{{ error }}</p> -->
  </div>
</template>

<script>
import { mapMutations } from 'vuex';
export default {
  data() {
    return {
      loginForm: {
        username: '',
        password: ''
      }
    };
  },
  methods: {
    ...mapMutations(['changeLogin']),
    login () {
      let _this = this;
      if (this.loginForm.username === '' || this.loginForm.password === '') {
        alert('账号或密码不能为空');
      } else {
        this.axios({
          method: 'post',
          url: '/admin/employee/login',
          data: _this.loginForm
        }).then(res => {
          console.log(res.data);
          _this.userToken = res.data.data.token;
          console.log(_this.userToken);
          // 将用户token保存到vuex中
          _this.changeLogin({ authentication: _this.userToken });
          _this.axios.get('/admin/employee/list').then(res1=>{
            _this.user=res1.data.data;
            console.log(_this.user);
            sessionStorage.setItem('user', JSON.stringify(_this.user));
            _this.$router.push('/');
          }).catch(err=>{
              console.log(err);
          })
          // sessionStorage.setItem('username', _this.loginForm.username);
          
          alert('登陆成功');

        }).catch(error => {
          alert('账号或密码错误');
          console.log(error);
        });
      }
    }
  }
}
</script>

<style scoped>
.login-container {
  width: 100%;
  max-width: 400px;
  margin: 30px auto;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  color: #333;
}

.form-control {
  margin-bottom: 15px;
  position: relative;
}

.form-control label {
  display: block;
  margin-bottom: 5px;
}

.form-control input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.login-btn {
  display: block;
  width: 100%;
  padding: 10px;
  border: none;
  background-color: #007bff;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

.login-btn:hover {
  background-color: #0056b3;
}

.error-message {
  color: red;
  text-align: center;
  margin-top: 5px;
}

/* 响应式设计 */
@media (max-width: 600px) {
  .login-container {
    padding: 15px;
  }
}
</style>
